/*
 * This program handles users and passwords
 */

#include <stdio.h>
#include <stdlib.h>

/* 
 * Function to authenticate users
 * 
 * Returns 
 * 	    0 authentication failed 
 *		1 if authentication was successful 
 */
int authenticate(char * username, char * password);

int authenticate(char * username, char * password){
	FILE *file;
	char *mode = "rt";
	char outputFilename[] = "users.txt";

	// Open the file
	file = fopen(outputFilename, mode);

	if (file == NULL) {
		fprintf(stderr, "Can't open output file %s!\n", outputFilename);
		exit(1);
	}
	
	int authenticated = 0;
  	int buffer_size = 200;
	int count = 0;
  	char line_buffer[buffer_size];  
  	
	while( fgets(line_buffer, buffer_size, file) != NULL && authenticated == 0 ){      
		if(line_buffer[0] != '#'){ // Skip comments				
			char * token;
			char * cur_username;
			char * cur_password;
			
			token = strtok(line_buffer," \n");
															
			int coloumn = 1;
			while (token != NULL){
				
				switch(coloumn){
					case 1 : cur_username = token; break;
					case 2 : cur_password = token; break; 			
				}
				
				token = strtok(NULL, " \n");
				coloumn++;			
			}

			if( strcmp(cur_username, username) == 0 &&  strcmp(cur_password, password) == 0 ){			
				authenticated = 1;
			}
		}
	}

	return authenticated;
}

/* 
 * main function for testing 
 */
/*int main(void){
	// Tests	
	printf("Test authentication failed: (should be 0) is:%d\n", authenticate(&"sonni", &"4321")); 		
	printf("Test authentication succeded: (should be 1) is:%d\n", authenticate(&"sonni", &"1234")); 		
	
	exit(EXIT_SUCCESS); 
}*/
